<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        let money = 300;

        function getTime() {
            return Math.floor(Math.random() * 3000 + 1000);
        }

        // 买菜
        function buy(name) {
            let promise = new Promise(function(resolve,reject) {
                setTimeout(() => {
                    if (money >= 50) {
                        money -= 50;
                        resolve(name);
                    } else {
                        reject(name);
                    }
                },getTime())
            });
            return promise;
        }

        function eat() {
            let arr = ["牛肉","毛肚","鸭肠","鸭血","蟹肉","虾滑","黄喉","肥牛","脑花"];
            let promises = [];
            for (let v of arr) {
                promises.push(buy(v));
            }
            // Promise.all，返回一个promise对象。当传入promise数组中所有Promise全部成为完成状态，最终完成
            // 缺陷：如果数组中的promise对象，有一个没有成功，那么最终状态不算做成功
            Promise.all(promises).then(res => {
                for (let v of res) {
                    console.log("买回来了：",v);
                }
                console.log("都买回来了，开始");
            },res => {
                for (let v of res) {
                    console.log("没有买回来：",v);
                }
            })
            
        }

        eat();

    </script>
</body>
</html>